/**
 * 用户头像
 */
import { FC, useEffect, useState } from "react";
import { Avatar, Dropdown, Typography } from "antd";
import { observer, inject } from "mobx-react";
import { UserOutlined } from "@ant-design/icons";
import { Link } from "react-router-dom";
import { ITStore } from "../../store";
import { logoutUser } from "../../utils/login";

type TProp = {
  store: ITStore;
};

const UserHead: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  const {
    languageStore: { lang },
    userStore: { getUserInfo, logUserOut },
    globalStore: { userMenu },
  } = store;

  const [menuItems, setMenuItems] = useState<any>([]);

  const logoutClick = async () => {
    const result = await logUserOut();
      if (!result) {
        logoutUser();
      }
  }

  useEffect(() => {
    let temp: any = [];
    userMenu.forEach((item) => {
      let { value, langkey, path } = item;
      if (value === "usermodify" && path) {
        temp.push({
          key: value,
          label: <Link to={path} >{lang[langkey]}</Link>
        })
      } else if (value === "loginout") {
        temp.push({
          key: value,
          label: <Typography.Link onClick={logoutClick} >{lang[langkey]}</Typography.Link>
        })
      }
    });
    setMenuItems(temp)

  }, [userMenu, lang]);

  // 用户名
  const [userName, setUserName] = useState("");
  useEffect(() => {
    let tempUserInfo = getUserInfo();
    setUserName(tempUserInfo?.account);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Dropdown menu={{ items: menuItems }}>
      <div>
        <Avatar icon={<UserOutlined />} /> {userName}
      </div>
    </Dropdown>
  );
};

export default inject("store")(observer(UserHead));
